<!DOCTYPE html>
<html>
<head>
	<title>生成二叉树</title>
</head>
<body>
<script type="text/javascript">
const targetArr = [8,3,10,1,6,14,4,7,13];//要遍历的数组
</script>
<script type="text/javascript">
function Node(data) {
    this.data = data;
}
function BST(){
    this.root = null;
    this.insert = function(data) {
        let n = new Node(data);
        if(!this.root) {
            this.root = n;
        }else {
            let result = [this.root];//入队
            while(result.length) {
                let cur = result.shift();//出队
                if(!cur.left) {
                    cur.left = n;
                    break;
                }else if(!cur.right) {
                    cur.right = n;
                    break;
                }else {
                    result.push(cur.left);//入队
                    result.push(cur.right);//入队
                }
            }
        }
    };
}
function genBST(list){
    let t = new BST();

    if(list && list.length > 0){
        list.forEach((data)=>{
            t.insert(data);
        })
    }

    return t;
}
const bst1 = genBST(targetArr);
console.log(bst1);
const bst2 = genBST();
bst2.insert(8);
bst2.insert(3);
bst2.insert(10);
bst2.insert(11);
bst2.insert(1);
console.log(bst2);
</script>
</body>
</html>